from django.shortcuts import render

# Create your views here.
from django.http.response import HttpResponse
from django.shortcuts import redirect
from django.http.response import HttpResponseRedirect
from django.views.decorators.http import require_http_methods


def set_cookie(request):
    """设置/保存/更新Cookie"""
    response = HttpResponse()
    # 生成cookie
    """
    参数列表：
    key,键/变量
    value,值/内容
    max_age=None,设置cookie的有效时间，单位秒
    expire=None,设置cookie的过期时间戳
        datetime.now().timestamp() 获取时间戳
        int(time.time() * 1000)  获取毫秒时间戳
        datetime.now().timestamp() 获取毫秒时间戳        
    path=None, 当前cookie是否只能在公共路径下使用，None表示在同一域名下，任意路径都可以使用
    domain=None,  当前cookie是否只能在指定同一域名下使用，None表示在当前服务器所在域名下使用
    secure=False,  当前cookie是否只能在https协议下使用，False表示也能在http协议下使用
    httponly=False,  当前cookie是否只能在http协议下使用，False表示也能在其他协议下使用 
    """
    response.set_cookie("uname", "xiaoming", max_age=5)
    response.set_cookie("uid", 100, max_age=180)
    # 设置cookie时间，不设置过期时间，默认cookie有效期就是浏览器关闭时自动删除
    # 会话结束时浏览器会自动删除没有设置有效的cookie，而设置有效期的cookie只会在到期时删除
    response.set_cookie("is_login", True, )
    return response


def get_cookie(request):
    """读取cookie,通过request.COOKIES可以获取客户端发送过来的cookie"""
    print(request.COOKIES)  # 获取客户端发送过来的cookie
    print("uid", request.COOKIES.get("uid"))  # 获取指定名称的cookie
    print("uname", request.COOKIES.get("uname"))  # 不存在或过期的cookie则不会被HTTP浏览器携带到请求头服务端
    # cookie的修改，与添加一致，cookie的重复变量名会覆盖
    response = HttpResponse("OK")
    response.set_cookie("uname", "xiaohong", max_age=20)
    return response


def del_cookie(request):
    """直接删除cookie在服务端是做不到的，因为cookie保留在客户端，我们需要通知客户端自己去删除"""
    # 告诉浏览器，cookie过期了
    response = HttpResponse("cookie过期了")
    response.set_cookie("uid", "", 0)  # 设置有效期为0秒，当服务器接受响应内容时会自动删除
    return response


def login(request):
    """登录页面"""
    if request.method == "GET":
        """显示登录表单"""
        content = """
        <form action="/cookie/login/" method="POST">
            登录账号：<input type="text" name="username"><br>
            登录密码：<input type="password" name="password"><br>
            <button>登录</button>
        </form>
        """
        return HttpResponse(content)
    elif request.method == "POST":
        """处理登录信息"""
        username = request.POST.get("username")
        password = request.POST.get("password")
        # 到数据库中查询当前账号密码是否正确
        from hashlib import sha256
        sha = sha256()
        sha.update(password.encode())
        hash_pwd = sha.hexdigest()
        if username == "root" and hash_pwd == "8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92":
            """登录成功"""
            # 记录登录状态
            response = HttpResponseRedirect("/cookie/info/")
            response.set_cookie("username", username)
            response.set_cookie("is_login", True, max_age=30 * 60)
        else:
            """登录失败"""
            response = HttpResponseRedirect("/cookie/login/")
            response["status"] = "fail"
        return response

@require_http_methods(["GET"])
def login(request):
    """显示登录表单"""
    content = """
    <form action="/cookie/login_handle/" method="POST">
        登录账号：<input type="text" name="username"><br>
        登录密码：<input type="password" name="password"><br>
        <button>登录</button>
    </form>
    """
    return HttpResponse(content)

@require_http_methods(["POST"])
def login_handle(request):
    """处理登录信息"""
    username = request.POST.get("username")
    password = request.POST.get("password")
    # 到数据库中查询当前账号密码是否正确
    from hashlib import sha256
    sha = sha256()
    sha.update(password.encode())
    hash_pwd = sha.hexdigest()
    if username == "root" and hash_pwd == "8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92":
        """登录成功"""
        # 记录登录状态
        response = HttpResponseRedirect("/cookie/info/")
        response.set_cookie("username", username)
        response.set_cookie("is_login", True, max_age=30 * 60)
    else:
        """登录失败"""
        response = HttpResponseRedirect("/cookie/login/")
        response["status"] = "fail"
    return response

def info(request):
    """用户中心-用户信息页面"""
    username = request.COOKIES.get("username")
    is_login = request.COOKIES.get("is_login",False)
    if username != "root" or not is_login:
        """未登录"""
        return redirect("/cookie/login/")
    return HttpResponse(f"当前页面显示用户：{username}的信息")